#!/usr/bin/env python3
"""
Docker部署验证脚本
"""
import sys
import os
import subprocess
import yaml
import json
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

def check_docker_installation():
    """检查Docker安装"""
    print("检查Docker安装...")
    
    try:
        result = subprocess.run(['docker', '--version'], 
                              capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            print(f"[OK] Docker已安装: {result.stdout.strip()}")
            return True
        else:
            print("[ERROR] Docker未安装或无法运行")
            return False
    except (subprocess.TimeoutExpired, FileNotFoundError):
        print("[ERROR] Docker未安装")
        return False

def check_docker_compose():
    """检查Docker Compose安装"""
    print("\n检查Docker Compose安装...")
    
    try:
        result = subprocess.run(['docker-compose', '--version'], 
                              capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            print(f"[OK] Docker Compose已安装: {result.stdout.strip()}")
            return True
        else:
            print("[ERROR] Docker Compose未安装或无法运行")
            return False
    except (subprocess.TimeoutExpired, FileNotFoundError):
        print("[ERROR] Docker Compose未安装")
        return False

def check_docker_compose_syntax():
    """检查docker-compose.yml语法"""
    print("\n检查docker-compose.yml语法...")
    
    try:
        with open('docker-compose.yml', 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        
        # 检查必需的服务
        services = config.get('services', {})
        required_services = ['web']
        
        for service in required_services:
            if service in services:
                print(f"[OK] 服务 {service} 配置正确")
            else:
                print(f"[ERROR] 缺少必需的服务: {service}")
                return False
        
        # 检查端口配置
        ports = {}
        for service_name, service_config in services.items():
            if 'ports' in service_config:
                for port_mapping in service_config['ports']:
                    if ':' in port_mapping:
                        host_port = port_mapping.split(':')[0]
                        ports[host_port] = service_name
        
        print(f"[OK] 端口映射配置: {ports}")
        
        # 检查数据卷
        volumes = config.get('volumes', {})
        print(f"[OK] 数据卷配置: {list(volumes.keys())}")
        
        return True
        
    except Exception as e:
        print(f"[ERROR] docker-compose.yml语法错误: {e}")
        return False

def check_nginx_config():
    """检查nginx.conf配置"""
    print("\n检查nginx.conf配置...")
    
    try:
        with open('nginx.conf', 'r', encoding='utf-8') as f:
            config = f.read()
        
        # 检查必需的配置块
        required_blocks = ['events {', 'http {', 'server {']
        for block in required_blocks:
            if block in config:
                print(f"[OK] 配置块 {block.strip()} 存在")
            else:
                print(f"[ERROR] 缺少配置块: {block.strip()}")
                return False
        
        # 检查upstream配置
        if 'upstream web_backend' in config:
            print("[OK] Web后端配置正确")
        else:
            print("[ERROR] 缺少Web后端配置")
            return False
        
        return True
        
    except Exception as e:
        print(f"[ERROR] nginx.conf读取错误: {e}")
        return False

def check_project_structure():
    """检查项目结构"""
    print("\n检查项目结构...")
    
    required_files = [
        'Dockerfile',
        'docker-compose.yml',
        'nginx.conf',
        'requirements.txt',
        'main.py',
        'start_web.py',
        'run.py',
        'init_db.py'
    ]
    
    required_dirs = [
        'core',
        'models',
        'services',
        'api',
        'templates',
        'static',
        'tests'
    ]
    
    missing_files = []
    missing_dirs = []
    
    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"[OK] 文件: {file_path}")
        else:
            print(f"[ERROR] 缺少文件: {file_path}")
            missing_files.append(file_path)
    
    for dir_path in required_dirs:
        if os.path.exists(dir_path):
            print(f"[OK] 目录: {dir_path}/")
        else:
            print(f"[ERROR] 缺少目录: {dir_path}/")
            missing_dirs.append(dir_path)
    
    if missing_files or missing_dirs:
        return False
    
    return True

def check_dependencies():
    """检查依赖文件"""
    print("\n检查依赖文件...")
    
    try:
        with open('requirements.txt', 'r') as f:
            dependencies = f.read().strip().split('\n')
        
        required_packages = [
            'fastapi',
            'uvicorn',
            'sqlalchemy',
            'pydantic',
            'passlib',
            'python-jose[cryptography]',
            'bcrypt'
        ]
        
        for package in required_packages:
            found = any(package in dep for dep in dependencies)
            if found:
                print(f"[OK] 依赖: {package}")
            else:
                print(f"[WARNING] 依赖可能缺失: {package}")
        
        return True
        
    except Exception as e:
        print(f"[ERROR] 依赖文件读取错误: {e}")
        return False

def check_system_config():
    """检查系统配置"""
    print("\n检查系统配置...")
    
    try:
        sys.path.insert(0, '.')
        from core.config import get_settings
        settings = get_settings()
        
        print(f"[OK] 应用名称: {settings.app_name}")
        print(f"[OK] Web端口: {settings.web_port}")
        print(f"[OK] MCP端口: {settings.mcp_port}")
        print(f"[OK] 数据库: {settings.database_url}")
        print(f"[OK] 日志文件: {settings.log_file}")
        print(f"[OK] 服务器日志: {settings.server_log_file}")
        
        return True
        
    except Exception as e:
        print(f"[ERROR] 系统配置检查失败: {e}")
        return False

def generate_deployment_summary():
    """生成部署摘要"""
    print("\n" + "="*60)
    print("Docker部署配置验证完成")
    print("="*60)
    
    print("\n📋 部署配置摘要:")
    print("  • Web界面端口: 8000")
    print("  • API服务端口: 8001")
    print("  • MCP服务端口: 8002")
    print("  • Redis端口: 6379")
    print("  • Nginx端口: 80/443")
    
    print("\n📁 数据目录:")
    print("  • 上传文件: ./uploads/")
    print("  • 解析结果: ./parsed_results/")
    print("  • 日志文件: ./logs/")
    print("  • 数据库文件: ./app.db")
    
    print("\n🚀 快速启动命令:")
    print("  • 仅Web界面: docker-compose up -d")
    print("  • 完整部署: docker-compose --profile redis --profile api up -d")
    print("  • 初始化数据: docker-compose --profile init up init")
    
    print("\n🌐 访问地址:")
    print("  • Web界面: http://localhost:8000/web/")
    print("  • API文档: http://localhost:8000/docs")
    print("  • 健康检查: http://localhost:8000/api/v1/health")
    
    print("\n👤 默认账户:")
    print("  • 管理员: admin / admin123")
    print("  • 测试用户: testuser / testpass123")
    
    print("\n📚 详细文档:")
    print("  • 部署指南: DOCKER_DEPLOYMENT.md")
    print("  • 项目文档: README.md")
    print("  • CLAUDE指导: CLAUDE.md")

def main():
    print("MinerU文档解析系统 - Docker部署验证")
    print("="*60)
    
    checks = [
        ("Docker安装", check_docker_installation),
        ("Docker Compose安装", check_docker_compose),
        ("Docker Compose语法", check_docker_compose_syntax),
        ("Nginx配置", check_nginx_config),
        ("项目结构", check_project_structure),
        ("依赖文件", check_dependencies),
        ("系统配置", check_system_config)
    ]
    
    results = []
    for check_name, check_func in checks:
        try:
            result = check_func()
            results.append((check_name, result))
        except Exception as e:
            print(f"[ERROR] {check_name}检查失败: {e}")
            results.append((check_name, False))
    
    # 生成摘要
    generate_deployment_summary()
    
    # 输出结果
    print("\n" + "="*60)
    print("验证结果:")
    print("="*60)
    
    passed = 0
    total = len(results)
    
    for check_name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"  {check_name}: {status}")
        if result:
            passed += 1
    
    print(f"\n总计: {passed}/{total} 项检查通过")
    
    if passed == total:
        print("\n🎉 所有检查通过！系统已准备好进行Docker部署")
        return True
    else:
        print(f"\n⚠️  有 {total - passed} 项检查失败，请修复后重新运行")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)